<?php

namespace app\admin\controller;

use app\AdminBaseController;

class User extends AdminBaseController{

    public function login(){
        if($this->request->isAjax()){
            $post = $this->request->post();
            $map['username'] = trim($post['username']);
            $admin = \app\admin\model\Admin::where($map)->findOrEmpty();
            if($admin->isEmpty()) return json(['code'=>-2,'message'=>'账号不存在']);
            if($admin->status==0) return json(['code'=>-1,'message'=>'账号已被禁用']);
            $inputPass = md5(trim($post['password']));
            if($admin->password != $inputPass) return json(['code'=>-3,'message'=>'密码错误']);

            $admin->last_login_time = date('Y-m-d H:i:s',time());
            $admin->last_login_ip = $this->request->ip();
            $admin->save();
            // 存储session
            session('admin',['admin_id'=>$admin->id,'username'=>$admin->username,'realname'=>$admin->realname,'mobile'=>$admin->mobile]);
            return json(['code'=>0,'message'=>'登录成功']);
        } else {
            return view();
        }
    }

    public function logout(){
        session('admin',null);
        echo '<script>window.location.href="http://tp6.com/admin/user/login.html"</script>';
    }

}